package sessao;

import java.util.ArrayList;

import beans.Cookie;

public class Sessao {
	
	private static Sessao sessao = null;
	private static final long tempoExpiracao = 2*1000*60;
	private ArrayList<Cookie> cookies = new ArrayList<Cookie>();
	private Sessao(){
		
	}
	
	public static Sessao getSessao(){
		if(sessao == null){
			sessao = new Sessao();
		}
		return sessao;
	}
	public void iniciarSessao(Cookie cookie){		
		boolean ativo = false;
		for (Cookie coo : cookies) {
			if(cookie.getChave().equals(coo.getChave())){
				if(cookie.getValor().equals(coo.getValor())){
					if(coo.getExpira().getTime()+tempoExpiracao > System.currentTimeMillis()){
						coo.getExpira().setTime(System.currentTimeMillis()+tempoExpiracao);
						ativo = true;
					}
				}				
			}
		}
		if(!ativo){
			cookies.add(cookie);	
		}
	}
	
	public boolean validarCookie(Cookie cookie){
		for (Cookie coo : cookies) {
			if(cookie.getChave().trim().equals(coo.getChave().trim())){
				if(cookie.getValor().trim().equals(coo.getValor().trim())){
					if(cookie.getExpira().getTime()+tempoExpiracao > System.currentTimeMillis()){
						coo.getExpira().setTime(System.currentTimeMillis()+tempoExpiracao);
						System.err.println("Sessao renovada");
						return true;
					}
				}				
			}			
		}
		return false;
	}
	
	public boolean validarToken(Cookie cookie){
		for (Cookie coo : cookies) {
			if(cookie.getChave().trim().equals(coo.getChave().trim())){
				if(cookie.getValor().trim().equals(coo.getValor().trim())){
					if(coo.getExpira().getTime()+tempoExpiracao > System.currentTimeMillis()){
						coo.getExpira().setTime(System.currentTimeMillis()+tempoExpiracao);
						System.err.println("Sessao renovada");
						return true;
					}
				}				
			}			
		}
		return false;
	}
	
	public boolean destruirSessao(Cookie cookie){
		
		boolean removido = false;
		int index = 0;
		for (Cookie coo : cookies) {			
			if(cookie.getChave().trim().equals(coo.getChave().trim())){
				cookies.remove(index);
				removido = true;
				break;
			}
			index++;
		}
		return removido;
	}
	public void limparCookies(){
		if(cookies.size()>0){
			for (Cookie coo : cookies) {
				if(coo.getExpira().getTime()+tempoExpiracao < System.currentTimeMillis()){
					System.out.println(coo.getChave()+" removido");
					cookies.remove(coo);
				}
			}
		}		
	}
}
